package com.audaque.springboot.foshanupload.web.raspcloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.audaque.springboot.foshanupload.core.util.encode.SpringBase64Utils;
import com.audaque.springboot.foshanupload.web.raspcloud.entity.User;
import com.audaque.springboot.foshanupload.web.raspcloud.mapper.UserMapper;
import com.audaque.springboot.foshanupload.web.raspcloud.req.ext.RegisterReq;
import com.audaque.springboot.foshanupload.web.raspcloud.req.ext.UserCreateReq;
import com.audaque.springboot.foshanupload.web.raspcloud.req.ext.UserUpdateReq;
import com.audaque.springboot.foshanupload.web.raspcloud.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author chinaben
 * @since 2025-07-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    public void register(RegisterReq req) throws Exception {
        User entity = BeanUtil.toBean(req, User.class);
        register(entity);
    }

    private void register(User user) throws Exception {
        // 查询是否有相同用户名的用户，有则响应"该用户名已注册"
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User existUser = baseMapper.selectOne(queryWrapper);
        if (existUser != null) {
            throw new Exception("该用户名已注册");
        }
        // 将密码进行加密操作
        String base64 = user.getPassword();
        String pw = SpringBase64Utils.decode(base64);
        String passwordMd5 = SecureUtil.md5(pw);
        user.setPassword(passwordMd5);
        user.setPasswordExpireTime(LocalDateTime.now().plusDays(30));
        // 保存到数据库
        baseMapper.insert(user);

    }

    public void save(UserCreateReq req) throws Exception {
        User entity = BeanUtil.toBean(req, User.class);
        register(entity);
    }

    public boolean updateById(UserUpdateReq req) {
        User entity = BeanUtil.toBean(req, User.class);
        return SqlHelper.retBool(getBaseMapper().updateById(entity));
    }
}
